Fruit into Baskets

Medium

Question

You're given an array of integers that represent a single line of trees with one fruit, where each integer value represents the type of fruit.

Your objective is to collect as much fruit as possible while following these conditions:

  • You can only pick fruit starting from left to right
  • You only have two baskets to hold two different types of fruits
  • When you reach a third type of fruit that can't be put into your baskets, you must stop picking altogether
  • There is no limit to the amount of fruit each basket can hold

Return the maximum number of fruit you can pick.

Input: [1, 0, 2, 2, 1, 2]

Output: 4

We can pick from trees [2, 2, 1, 2]. If we had started at the first tree, we would only pick from trees [1, 0]. If we had started at the second tree, we would only pick from trees [0, 2, 2].

Input: [1, 2, 1]

Output: 3

We can pick from all three trees.

Input: [2, 4, 3, 4, 4]

Output: 4

We can pick from trees [4, 3, 4, 4]. If we had started at the first tree, we would only pick from trees [2, 4].

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

What is the maximum number of fruit you can pick from this line of trees? [4, 3, 3, 5, 3, 4]
1
2
3
4

Login or signup to save your code.

Notes